<?php
// application/lib/AuthAdapter.php
/**
 * demo-zf application
 *
 * lib\Lib_AuthAdapter
 *
 * @author Adam Pilacki <adam.pilacki@gmail.com>
 */
final class Lib_AuthAdapter
    implements Zend_Auth_Adapter_Interface
{
    private $_login = null;

    private $_password = null;

    const IDENTITY_SUCCESS  = 'demo-zf-cuccess';
    const IDENTITY_FAILURE  = 'demo-zf-failure';

    /**
     * Sets login and password for authentication
     *
     * @return void
     */
    public function __construct($login, $password) {
        $this->_login = (string) $login;
        $this->_password = (string) $password;
    }

    /**
     * Performs an authentication
     *
     * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
     * @return Zend_Auth_Result
     */
    public final function authenticate()
    {
        /* @var $user Model_UsersRow */
        $user = AdamP_Model::getTable('Users')->findOneByAuthProperties($this->_login, $this->_password);

        if (empty($user)) {
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, self::IDENTITY_FAILURE);
        }

        $userData = array(
            'id' => $user->id,
            'login' => $user->login,
        );

        /* store auth user data in session */
        Zend_Registry::get('sessionNamespace')->authUserData = $userData;

        /* used to check when $_SESSION expires */
        setcookie('authenticated', '1', null, '/');

        return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, self::IDENTITY_SUCCESS);
//        return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, self::IDENTITY_FAILURE);
    }
}